package com.ybt.router.tcp.sender.manager;

import org.apache.log4j.Logger;

import com.ybt.communicate.core.IConnection;
import com.ybt.communicate.core.IProtocol;
import com.ybt.communicate.core.exception.ProtocolException;
import com.ybt.communicate.core.manager.ProtocolManager;
import com.ybt.router.core.sender.ISender;
import com.ybt.router.core.sender.exception.MessageSenderException;
import com.ybt.router.core.sender.manager.ISenderManager;
import com.ybt.router.tcp.routertable.TCPAddress;
import com.ybt.router.tcp.routertable.TCPServiceRouter;
import com.ybt.router.tcp.routertable.manager.TCPRouterManager;
import com.ybt.router.tcp.sender.TCPSender;

public class TCPSenderManager implements ISenderManager{
    private static Logger logger = Logger.getLogger(TCPSenderManager.class);
    private static TCPSenderManager manager;
    
    private TCPSenderManager(){
        
    }
    
    public static TCPSenderManager getInstance(){
        if(manager==null){
            synchronized(TCPSenderManager.class){
                if(manager==null){
                    manager = new TCPSenderManager();
                }
            }
        }
        return manager;
    }
    
    public ISender getSender(String serviceName) throws MessageSenderException {
        // TODO Auto-generated method stub
        TCPServiceRouter router = TCPRouterManager.getInstance().getRouter(serviceName);
        if(router==null){
            throw new MessageSenderException("any service router information about " + serviceName);
        }
        TCPAddress add = (TCPAddress)router.getInAddress();
        if(logger.isDebugEnabled()){
            logger.debug("the sender for service " + serviceName + " is " + add.getAddressKey());
        }
        //获取协议
        IProtocol p = ProtocolManager.getInstance().getProtocol(add.getDestination());
        IConnection con = null;
        try {
            con = p.createConnection();
        } catch (ProtocolException e) {
            throw new MessageSenderException(e);
        }
        //创建sender
        TCPSender sender = new TCPSender();
        sender.setConnection(con);
        return sender;
    }

    public void startSender(String sendKey) throws MessageSenderException {
        // TODO Auto-generated method stub
        
    }

}
